/*
    muduo库练习使用
    实现一个翻译服务器 客户端发来一个单词 返回一个汉语单词
*/

 #include <iostream> 
#include <string>
#include <memory>
#include <unordered_map>
#include <muduo/net/TcpServer.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/Buffer.h>

class DictServer{
public:
    DictServer(int port)
    :_server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port), "DictServer", muduo::net::TcpServer::kReusePort)
    {
        // 设置连接建立&断开的回调处理
        _server.setConnectionCallback(std::bind(&DictServer::onConnection, this, std::placeholders::_1));
        // 设置收到消息的回调处理
        _server.setMessageCallback(std::bind(&DictServer::onMessage, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start(){
        _server.start();
        _baseloop.loop();
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn){
        // 判断连接是否建立或断开
        if (conn->connected()){
            std::cout << "连接建立..." << std::endl;
        }
        else{
            std::cout << "连接断开..." << std::endl;
        }
    }

    void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp){
        static std::unordered_map<std::string, std::string> dict = {
            {"hello", "你好"},
            {"world", "世界"},
            {"apple", "苹果"}};

        // 从缓冲区中读取全部数据
        std::string msg = buf->retrieveAllAsString();
        std::string res;
        auto it = dict.find(msg);
        if (it != dict.end()){
            res = it->second;
        }
        else{
            res = "未知单词";
        }

        // 发送处理后的数据
        conn->send(res);
    }

private:
    muduo::net::EventLoop _baseloop;
    muduo::net::TcpServer _server;
};

int main(){
    std::unique_ptr<DictServer> server(new DictServer(28080));
    server->start();
    return 0;
}